﻿//
//此代码由YFINGenerator自动生成
//Copyright (c) 段凯强 2013~2014
//2013-4-16 8:59:07
//
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Expression.Interactivity.Core;
using YFIN.View.FileServiceRef;
using YFIN.View.Lockbox;

namespace YFIN.View.ViewModels
{
    public class FileVM : INotifyPropertyChanged
    {
        #region INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
        #endregion

        #region 属性
        private ObservableCollection<ModelFile> _files;
        public ObservableCollection<ModelFile> Files
        {
            get
            {
                return _files;
            }
            set
            {
                if (_files != value)
                {
                    _files = value;
                    NotifyPropertyChanged("Files");
                }
            }
        }

        private ModelFile _currentDirectory;
        public ModelFile CurrentDirectory
        {
            get
            {
                return _currentDirectory;
            }
            set
            {
                if (_currentDirectory != value)
                {
                    _currentDirectory = value;
                    NotifyPropertyChanged("CurrentDirectory");
                }
            }
        }

        private ModelFile _currentFile;
        public ModelFile CurrentFile
        {
            get
            {
                return _currentFile;
            }
            set
            {
                if (_currentFile != value)
                {
                    _currentFile = value;
                    NotifyPropertyChanged("CurrentFile");
                }
            }
        }

        private ModelFile _cutFile;
        public ModelFile CutFile
        {
            get
            {
                return _cutFile;
            }
            set
            {
                if (_cutFile != value)
                {
                    _cutFile = value;
                    NotifyPropertyChanged("CutFile");
                }
            }
        }

        public ICommand AddFileCommand { get; private set; }
        public ICommand DownloadFileCommand { get; private set; }
        public ICommand DeleteCommand { get; private set; }
        public ICommand AddDirectoryCommand { get; private set; }
        public ICommand OpenDirectoryCommand { get; private set; }
        public ICommand BackDirectoryCommand { get; private set; }
        public ICommand RenameCommand { get; private set; }
        #endregion

        public FileVM()
        {
            AddFileCommand = new ActionCommand(AddFile);
            DownloadFileCommand = new ActionCommand(DownloadFile);
            DeleteCommand = new ActionCommand(Delete);
            AddDirectoryCommand = new ActionCommand(AddDirectory);
            OpenDirectoryCommand = new ActionCommand(OpenDirectory);
            BackDirectoryCommand = new ActionCommand(BackDirectory);
            RenameCommand = new ActionCommand(Rename);

            var client = new FileServiceClient();
            client.GetByUserNameCompleted += new EventHandler<GetByUserNameCompletedEventArgs>(client_GetByUserNameCompleted);
            client.GetByUserNameAsync(Stage.User.UserName);

            CurrentDirectory = null;
        }


        private readonly List<string> _data = new List<string>();
        public void AddFile()
        {
            var openFileDialog = new OpenFileDialog() { Filter = "(*.*)|*.*", Multiselect = false };
            if (openFileDialog.ShowDialog() == true)
            {
                FileInfo fileInfo = openFileDialog.File;
                Stream stream = fileInfo.OpenRead();

                while (stream.Position > -1 && stream.Position < stream.Length)
                {
                    long rest = stream.Length - stream.Position;
                    int len = (rest >= 6144) ? 6144 : (int)rest;
                    var fileData = new byte[len];
                    stream.Read(fileData, 0, len);
                    _data.Add(Convert.ToBase64String(fileData));
                }
                stream.Close();

                string type = fileInfo.Name.Substring(fileInfo.Name.LastIndexOf('.') + 1);
                CurrentFile = new ModelFile
                                  {
                                      Father = CurrentDirectory == null ? (long?) null : CurrentDirectory.No,
                                      Name = fileInfo.Name,
                                      Type = true,
                                      UserName = Stage.User.UserName,
                                  };
                var client = new FileServiceClient();
                client.AddCompleted += new EventHandler<AddCompletedEventArgs>(client_AddCompleted);
                client.AddAsync(CurrentFile, _data[0], false, Stage.User.Password);
            }
        }

        public void DownloadFile()
        {
            if (CurrentFile.Type)
            {
                var client = new FileServiceClient();
                client.DownloadCompleted += new EventHandler<DownloadCompletedEventArgs>(client_DownloadCompleted);
                client.DownloadAsync(CurrentFile.Name, Stage.User.Password, Stage.User.UserName);
            }
        }

        private void client_DownloadCompleted(object sender, DownloadCompletedEventArgs e)
        {
            if (e.Result != null)
            {
                string url = "UserData/" + CurrentFile.UserName + "/" + CurrentFile.Name;
                System.Windows.Browser.HtmlPage.Window.Navigate(new Uri(url, UriKind.Relative), "_blank");
            }
            else
            {
                MessageBox.Show("文件处理出现错误");
            }
        }

        public void Update()
        {
            try
            {
                CutFile.Father = CurrentDirectory == null ? (long?) null : CurrentDirectory.No;
                var client = new FileServiceClient();
                client.UpdateCompleted += new EventHandler<UpdateCompletedEventArgs>(client_UpdateCompleted);
                client.UpdateAsync(CutFile);
            }
            catch(Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }

        public void Delete()
        {
            var client = new FileServiceClient();
            client.DeleteCompleted += new EventHandler<DeleteCompletedEventArgs>(client_DeleteCompleted);
            client.DeleteAsync(CurrentFile);
        }

        public void AddDirectory()
        {
            CurrentFile = new ModelFile
                              {
                                  Father = CurrentDirectory == null ? (long?) null : CurrentDirectory.No,
                                  Type = false,
                                  UserName = Stage.User.UserName,
                                  Name = "新建文件夹",
                              };
            var w = new DirectoryDetail {DataContext = CurrentFile};
            w.Show();
            w.Closed +=
                (sender, e) =>
                {
                    if (w.DialogResult.HasValue && w.DialogResult.Value)
                    {
                        var client = new FileServiceClient();
                        client.AddDirectoryCompleted += new EventHandler<AddDirectoryCompletedEventArgs>(client_AddDirectoryCompleted);
                        client.AddDirectoryAsync(CurrentFile);
                    }
                };
        }

        public void OpenDirectory()
        {
            if(!CurrentFile.Type)
            {
                CurrentDirectory = CurrentFile;
                var client = new FileServiceClient();
                client.GetByFatherCompleted += new EventHandler<GetByFatherCompletedEventArgs>(client_GetByFatherCompleted);
                client.GetByFatherAsync(CurrentDirectory.No);
            }
        }

        public void BackDirectory()
        {
            if (CurrentDirectory != null && CurrentDirectory.Father != null)
            {
                var client = new FileServiceClient();
                client.GetByNoCompleted += new EventHandler<GetByNoCompletedEventArgs>(client_GetByNoCompleted);
                client.GetByNoAsync((long) CurrentDirectory.Father);
            }
            else if(CurrentDirectory != null)
            {
                CurrentDirectory = null;
                var client = new FileServiceClient();
                client.GetByUserNameCompleted += new EventHandler<GetByUserNameCompletedEventArgs>(client_GetByUserNameCompleted);
                client.GetByUserNameAsync(Stage.User.UserName);
            }
        }

        public void Rename()
        {
            var w = new DirectoryDetail { DataContext = CurrentFile };
            w.Show();
            w.Closed +=
                (sender, e) =>
                {
                    if (w.DialogResult.HasValue && w.DialogResult.Value)
                    {
                        var client = new FileServiceClient();
                        client.UpdateCompleted += new EventHandler<UpdateCompletedEventArgs>(client_UpdateCompleted);
                        client.UpdateAsync(CurrentFile);

                        string type = CurrentFile.Name.Substring(CurrentFile.Name.LastIndexOf('.') + 1);
                        CurrentFile.FileIcon = "/YFIN.View;component/Images/" + type + ".png";
                        CurrentFile.ShortName = CurrentFile.Name.Length > 15 ? CurrentFile.Name.Substring(0, 12) + "..." : CurrentFile.Name;
                    }
                };
        }


        public void SetCurrent(int index)
        {
            if (index >= 0)
            {
                CurrentFile = Files[index];
            }
        }

        private void client_AddCompleted(object sender, AddCompletedEventArgs e)
        {
            if (e.Result)
            {
                _data.RemoveAt(0);
                if (_data.Count == 0)
                {
                    var client = new FileServiceClient();
                    if (CurrentDirectory == null)
                    {
                        client.GetByUserNameCompleted +=
                            new EventHandler<GetByUserNameCompletedEventArgs>(client_GetByUserNameCompleted2);
                        client.GetByUserNameAsync(Stage.User.UserName);
                    }
                    else
                    {
                        client.GetByFatherCompleted +=
                            new EventHandler<GetByFatherCompletedEventArgs>(client_GetByFatherCompleted2);
                        client.GetByFatherAsync(CurrentDirectory.No);
                    }
                }
                else
                {
                    ((FileServiceClient)sender).AddAsync(CurrentFile, _data[0], true, Stage.User.Password);
                }
            }
        }

        private void client_GetByUserNameCompleted(object sender, GetByUserNameCompletedEventArgs e)
        {
            if(e.Result != null)
            {
                Files = e.Result;
            }
        }

        private void client_GetByUserNameCompleted2(object sender, GetByUserNameCompletedEventArgs e)
        {
            if (e.Result != null && e.Result.Count > 0)
            {
                Files.Add(e.Result[e.Result.Count - 1]);
            }
        }

        private void client_UpdateCompleted(object sender, UpdateCompletedEventArgs e)
        {
            if(e.Result)
            {
                if(CurrentDirectory == null)
                {
                    var client = new FileServiceClient();
                    client.GetByUserNameCompleted += new EventHandler<GetByUserNameCompletedEventArgs>(client_GetByUserNameCompleted);
                    client.GetByUserNameAsync(Stage.User.UserName);
                }
                else
                {
                    var client = new FileServiceClient();
                    client.GetByFatherCompleted += new EventHandler<GetByFatherCompletedEventArgs>(client_GetByFatherCompleted);
                    client.GetByFatherAsync(CurrentDirectory.No);
                }
            }
        }

        private void client_DeleteCompleted(object sender, DeleteCompletedEventArgs e)
        {
            if(e.Result)
            {
                try
                {
                    if (CurrentFile.Type)
                    {
                        Files.Remove(CurrentFile);
                    }
                }
                catch (Exception ex)
                {
                    //TODO 奇怪的被忽略掉的异常
                }
            }
        }

        private void client_AddDirectoryCompleted(object sender, AddDirectoryCompletedEventArgs e)
        {
            if(e.Result)
            {
                var client = new FileServiceClient();
                if (CurrentDirectory == null)
                {
                    client.GetByUserNameCompleted +=
                        new EventHandler<GetByUserNameCompletedEventArgs>(client_GetByUserNameCompleted2);
                    client.GetByUserNameAsync(Stage.User.UserName);
                }
                else
                {
                    client.GetByFatherCompleted +=
                        new EventHandler<GetByFatherCompletedEventArgs>(client_GetByFatherCompleted2);
                    client.GetByFatherAsync(CurrentDirectory.No);
                }
            }
        }

        private void client_GetByFatherCompleted(object sender, GetByFatherCompletedEventArgs e)
        {

            if (e.Result != null)
            {
                try
                {
                    Files = e.Result;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }

        private void client_GetByFatherCompleted2(object sender, GetByFatherCompletedEventArgs e)
        {

            if (e.Result != null && e.Result.Count > 0)
            {
                Files.Add(e.Result[e.Result.Count - 1]);
            }
        }

        private void client_GetByNoCompleted(object sender, GetByNoCompletedEventArgs e)
        {
            CurrentDirectory = e.Result;
            var client = new FileServiceClient();
            client.GetByFatherCompleted += new EventHandler<GetByFatherCompletedEventArgs>(client_GetByFatherCompleted);
            client.GetByFatherAsync(CurrentDirectory.No);
        }
    }
}